package amushen.base;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1649041813962248918L;

	private String uploadPath = "";
	private int maxPostSize = 1000 * 1024 * 1024;

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String filePathaa = this.getServletConfig().getServletContext()
				.getRealPath("/src");

		uploadPath = filePathaa;
		//System.out.println(uploadPath);

		res.setContentType("text/html;charset=UTF-8");
		res.getWriter().print("abc");
		req.setCharacterEncoding("UTF-8");

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(1024 * 20);

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(maxPostSize);
		try {
			List fileItems = upload.parseRequest(req);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					String name = item.getName();

					try {
						File skFile = new File(uploadPath +"\\"+ name);
						if (skFile.exists()) {
							skFile.delete();
							item.write(new File(uploadPath +"\\"+ name));

						} else {
							item.write(new File(uploadPath +"\\"+ name));
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

	}
}
